import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:karyo/karyo.dart';

class ManaUser {
  String userName;
  String userSign;
  String userAvatarUrl;
  String userEmail;
  String userRegisterTime;
  bool isManavip;
  String manavipStarts;
  int userLevel;
  String userID;
  String userGender;
  String userPassword;
  ImageProvider targetAvatarImage;

  ManaUser(
      {this.userName,
      this.userSign,
      this.userID,
      this.userAvatarUrl,
      this.userEmail,
      this.userRegisterTime,
      this.isManavip,
      this.manavipStarts,
      this.userLevel,
      this.userGender,
      this.userPassword,
      this.targetAvatarImage});

  static List<ManaUser> allFromResponse(String response) {
    var decodedJson = json.decode(response);
    print(decodedJson);
    return decodedJson['data']
        .cast<Map<String, dynamic>>()
        .map((obj) => ManaUser.fromMap(obj))
        .toList()
        .cast<ManaUser>();
  }

  static ManaUser fromMap(Map map) {
    // userAvatar
    ImageProvider targetAvatarImage;
    var userAvatarUrl = map['user_avatar_url'];
    if (userAvatarUrl == '' || userAvatarUrl == null) {
      userAvatarUrl = map['user_avatar_url_local'];
      targetAvatarImage = NetworkImage(API.MANA_HOST + userAvatarUrl);
    } else {
      if (userAvatarUrl != null && userAvatarUrl != '') {
        targetAvatarImage = NetworkImage(userAvatarUrl);
      } else {
        targetAvatarImage = AssetImage('assets/fitness_app/snack.png');
      }
    }

    var _userPassword = '';
    if (map.containsKey('user_password')) {
      _userPassword = map['user_password'];
    }

    return ManaUser(
      userName: map['user_name'],
      userSign: map['user_sign'],
      userAvatarUrl: map['user_avatar_url'],
      userEmail: map['user_email'],
      userRegisterTime: map['user_register_time'],
      isManavip: map['is_manavip'],
      manavipStarts: map['manavip_starts'],
      userLevel: map['user_level'],
      userGender: map['user_gender'],
      userID: map['user_id'].toString(),
      userPassword: _userPassword,
      targetAvatarImage: targetAvatarImage,
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['user_name'] = this.userName;
    data['user_sign'] = this.userSign;
    data['user_avatar_url'] = this.userAvatarUrl;
    data['user_email'] = this.userEmail;
    data['user_register_time'] = this.userRegisterTime;
    data['is_manavip'] = this.isManavip;
    data['manavip_starts'] = this.manavipStarts;
    data['user_level'] = this.userLevel;
    data['user_gender'] = this.userGender;
    data['user_id'] = this.userID;
    return data;
  }
}
